import axios from "axios"
import config from "@/config"
import store from "@/store"

let timer = null;

export async function post(url, data) {
    return await requestHandler('post', url, data)
}

export async function get(url, data) {
    return await requestHandler('get', url, data)
}

async function requestHandler(method, url, data) {
    const requestConfig = {
        method,
        url,
        baseURL: config.server.baseUrl,
        headers: {
            authorization: `Bearer ${localStorage.token}`
        }
    }
    requestConfig[method === 'get' ? 'params' : 'data'] = data;
    let res = null;
    try {
        store.commit('setLoading', true);
        res = await axios.request(requestConfig)
    } catch (e) {
        exceptionHandler(e);
        return {data: null, message: e.message};
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        store.commit('setLoading', false);
        clearTimeout(timer);
        timer = null;
    }, 100)
    return requestLaterHandler(res);
}

function requestLaterHandler(res) {
    exceptionHandler(res);
    return res['data'];
}

function exceptionHandler(e) {
    if (e.status === 200) return
    const code = e.message.replace("Request failed with status code ", '');
    switch (code) {
        case "401": //登录失效清空缓存重新登录
            for (const key in localStorage) {
                delete localStorage[key]
            }
            location.reload();
            break;
    }
}
